package com.biao.test_annotation.refect_test;

import com.biao.test_annotation.InitDemo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 方法调用测试
 */
public class CallMethod {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        Class<?> pathClass = Class.forName("com.biao.test_annotation.InitDemo");
        InitDemo initDemo = (InitDemo) pathClass.newInstance();     // newInstance() 会默认调用无参构造

        // getMethod() 只能调用public修饰的公有方法,私有方法要使用 getDeclaredMethod()
//        Method privateTest = pathClass.getMethod("privateTest");
        Method privateTest = pathClass.getDeclaredMethod("privateTest");
        privateTest.setAccessible(true);    // 必须要给权限,不然没法使用
        privateTest.invoke(initDemo);

        // 调用带参数的私有方法
        Method privateTest2 = pathClass.getDeclaredMethod("privateTest2", Integer.class, Integer.class);
        privateTest2.setAccessible(true);
        Integer intResult = (Integer) privateTest2.invoke(initDemo, 1, 1);
        System.out.println(intResult);

    }
}
